const fs = require('node:fs')
const path = require('node:path')

const rfidStorage = {
    storage: {},
    cache: {},
}

const timers = {

}


function writeLog(message) {
    const logString = `${new Date().toLocaleString()} --- ${message}`
    console.log(logString);

    // 绝对地址
    const logPath = path.resolve(__dirname, '../logs/log.txt')
    // 将日志写到文件中
    fs.appendFileSync(logPath, logString + '\n')
}


const onSetRfidData = (config) => {
    const { key, rfid, antenna } = config
    // console.log('config', config)
    // 测试 5 号天线
    if (antenna !== 5) return
    const { cache } = rfidStorage
    // 赋值初始值
    const ids = cache[key] || []

    const isExist = ids.includes(rfid)

    const timeKey = `${key}=${rfid}`
    clearTimeout(timers[timeKey])
    timers[timeKey] = setTimeout(() => {
        ids.splice(ids.indexOf(rfid), 1)
        writeLog(`${key}===${rfid} 离开`)
    }, 1800);

    // 不存在,添加
    if (rfid && !isExist) {
        // 进入时,如果有缓存,则删除缓存
        Object.keys(cache).map((key) => {
            const ids = cache[key] || []
            if (ids.includes(rfid)) {
                const timeKey = `${key}=${rfid}`
                clearTimeout(timers[timeKey])
                ids.splice(ids.indexOf(rfid), 1)
                writeLog(`${key}===${rfid} 离开`)
            }
        })


        ids.push(rfid)
        writeLog(`${key}===${rfid} 进入`)
    }

    cache[key] = ids
}


module.exports = {
    onSetRfidData
}